<template>
  <a-button shape="round" style="margin-right: 5px"
            type="primary" icon="plus" @click="addNew">新建</a-button>
</template>
<script>
import {createProps, guid} from '@/utils';

export default {
  name: 'AddNewButton',
  props: {
    config: createProps(Object, () => undefined),
    context: createProps(Object, () => undefined),
    dataSource: createProps(Array, () => []),
    subFormDefinition: createProps(Object),
    selectedRowId: createProps(String),
  },
  methods: {
    addNew() {
      let data = {};
      this.createFields(data);
      data.id = guid();
      this.dataSource.push(data);
      data._isNew = true;
      this.$nextTick(() => {
        this.$emit('updateSubFormData')
      })
    },
    createFields(data) {
      let fields = this.subFormDefinition && this.subFormDefinition.fields || [];
      let auth = {}, fieldActions = this.context.action.fieldActions;
      let required = {};
      fields.forEach(field => {
        let fieldAction = fieldActions.find(f => f.fieldId === field.id);
        this.$set(auth, field.fieldName, fieldAction && fieldAction.auth || AuthType.edit);
        this.$set(required, field.fieldName, fieldAction && fieldAction.required || false);
        if (field.fieldName) {
          this.$set(data, field.fieldName, undefined);
        }
        if (field.fieldTitleName) {
          this.$set(data, field.fieldTitleName, undefined);
        }
      });
      this.$set(data, '_auth', auth);
      this.$set(data, '_required', required);
    },
  }
};
</script>